<template>
  <div class="main-content">
    <a-form layout="inline" :form="state.tableParams">
      <a-row :gutter="8" type="flex">
        <a-col :span="24" v-if="false && state.checkedList.length === 0">
          <a-card title="待办统计" style="width: 100%">
            <template #extra>
              <span
                @click="onTodoCardTabChange('personal', 'todoKey')"
                :style="{
                  color: state.todoKey === 'personal' ? '#52acff' : ''
                }"
                >个人</span
              >
              <span v-if="state.isAdmin"> / </span>
              <span
                v-if="state.isAdmin"
                @click="onTodoCardTabChange('department', 'todoKey')"
                :style="{
                  color: state.todoKey === 'department' ? '#52acff' : ''
                }"
                >部门</span
              >
            </template>

            <a-row type="flex" :gutter="8">
              <a-col :span="8">
                <div class="card-list">
                  <div class="card-list-item">
                    <div>当前待处理待办共计</div>
                    <div class="card-list-item-desc">
                      <span class="card-list-item-value">{{
                        todoHeaderInfo.processing
                      }}</span>
                      <span class="card-list-item-unit">条</span>
                    </div>
                  </div>
                </div>
              </a-col>
              <a-col :span="8">
                <div class="card-list">
                  <div class="card-list-item" style="margin-left: 10px">
                    <div>我今日发起的待办共计</div>
                    <div class="card-list-item-desc">
                      <span class="card-list-item-value">{{
                        todoHeaderInfo.initiation
                      }}</span>
                      <span class="card-list-item-unit">条</span>
                    </div>
                  </div>
                </div>
              </a-col>
              <a-col
                :span="8"
                v-for="(col, index) in todoHeaderInfo.categoricalStatistics"
                :key="index"
                @click="todoTypeClickHandler(col.cps)"
              >
                <div class="card-list">
                  <div class="card-list-item">
                    <div>{{ col.label }}</div>
                    <div class="card-list-item-desc">
                      <span class="card-list-item-value">{{ col.value }}</span>
                      <span class="card-list-item-unit">件</span>
                    </div>
                  </div>
                </div>
              </a-col>
            </a-row>
          </a-card>
        </a-col>
        <a-col :span="24" v-else>
          <a-row :gutter="8" class="card-content-flex" type="flex">
            <a-col v-if="firstColShow" :flex="13" style="width: 0">
              <a-card title="订单采购">
                <template #extra v-if="state.isAdmin">
                  <span
                    @click="
                      onTabChange('personal', 'card1Key', 'orderPurchaseInfo')
                    "
                    :style="{
                      color:
                        state.card1Key === 'personal'
                          ? 'rgba(24, 144, 255, 1)'
                          : 'rgba(78, 89, 105, 1)'
                    }"
                    >个人</span
                  >
                  <span> / </span>
                  <span
                    @click="
                      onTabChange('department', 'card1Key', 'orderPurchaseInfo')
                    "
                    :style="{
                      color:
                        state.card1Key === 'department'
                          ? 'rgba(24, 144, 255, 1)'
                          : 'rgba(78, 89, 105, 1)'
                    }"
                    >部门</span
                  >
                </template>

                <a-row type="flex" :gutter="10">
                  <a-col
                    :span="8"
                    v-for="(item, index) in orderPurchaseInfo"
                    :key="index"
                  >
                    <div class="card-list">
                      <div class="card-list-item">
                        <div>{{ item.label }}</div>
                        <div class="card-list-item-desc">
                          <span
                            @click="
                              orderPurchaseInfoClickHandler(
                                item,
                                state.card1Key,
                                false
                              )
                            "
                            class="card-list-item-value"
                          >
                            {{ item.value }}
                            <span>条</span>
                          </span>
                        </div>
                      </div>
                      <div class="card-list-line" />
                      <div class="card-list-item">
                        <div>
                          {{
                            item.label === '总数'
                              ? '关联SKC'
                              : item.label + 'SKC'
                          }}
                        </div>
                        <div class="card-list-item-desc">
                          <span
                            @click="
                              orderPurchaseInfoClickHandler(
                                item,
                                state.card1Key,
                                false
                              )
                            "
                            class="card-list-item-value"
                          >
                            {{ item.skcValue }}
                            <span>件</span>
                          </span>
                        </div>
                      </div>
                    </div>
                  </a-col>
                </a-row>
              </a-card>
            </a-col>
            <a-col v-if="secondColShow" :flex="4.5" style="width: 0">
              <a-card title="对账任务">
                <template #extra v-if="state.isAdmin">
                  <span
                    @click="
                      onTabChange('personal', 'card2Key', 'checkAccountInfo')
                    "
                    :style="{
                      color:
                        state.card2Key === 'personal'
                          ? 'rgba(24, 144, 255, 1)'
                          : 'rgba(78, 89, 105, 1)'
                    }"
                    >个人</span
                  >
                  <span> / </span>
                  <span
                    @click="
                      onTabChange('department', 'card2Key', 'checkAccountInfo')
                    "
                    :style="{
                      color:
                        state.card2Key === 'department'
                          ? 'rgba(24, 144, 255, 1)'
                          : 'rgba(78, 89, 105, 1)'
                    }"
                    >部门</span
                  >
                </template>
                <a-row type="flex" :gutter="8">
                  <a-col
                    :span="24"
                    v-for="(item, index) in checkAccountInfo"
                    :key="index"
                  >
                    <div class="card-list">
                      <div class="card-list-item">
                        <div>{{ item.label }}</div>
                        <div class="card-list-item-desc">
                          <span
                            @click="checkAccountInfoClickHandler(item)"
                            class="card-list-item-value"
                          >
                            {{ item.value }}
                            <span>条</span>
                          </span>
                        </div>
                      </div>
                      <div class="card-list-line" />
                      <div class="card-list-item">
                        <div>关联SKC</div>
                        <div class="card-list-item-desc">
                          <span
                            @click="checkAccountInfoClickHandler(item, true)"
                            class="card-list-item-value"
                          >
                            {{ item.skcValue }}
                            <span>件</span>
                          </span>
                        </div>
                      </div>
                    </div>
                  </a-col>
                </a-row>
              </a-card>
            </a-col>
            <a-col v-if="thirdColShow" :flex="3" style="width: 0">
              <a-card title="询期" class="inquiry-card">
                <template #extra v-if="state.isAdmin">
                  <span
                    @click="onTabChange('personal', 'card3Key', 'inquiryInfo')"
                    :style="{
                      color:
                        state.card3Key === 'personal'
                          ? 'rgba(24, 144, 255, 1)'
                          : 'rgba(78, 89, 105, 1)'
                    }"
                    >个人</span
                  >
                  <span> / </span>
                  <span
                    @click="
                      onTabChange('department', 'card3Key', 'inquiryInfo')
                    "
                    :style="{
                      color:
                        state.card3Key === 'department'
                          ? 'rgba(24, 144, 255, 1)'
                          : 'rgba(78, 89, 105, 1)'
                    }"
                    >部门</span
                  >
                </template>
                <a-row type="flex" :gutter="8">
                  <a-col
                    :span="24"
                    v-for="(item, index) in inquiryInfo"
                    :key="index"
                  >
                    <div class="card-list">
                      <div class="card-list-item">
                        <div>{{ item.label }}</div>
                        <div class="card-list-item-desc">
                          <span
                            @click="inquiryClickHandler(item)"
                            class="card-list-item-value"
                          >
                            {{ item.value }}
                            <span>条</span>
                          </span>
                        </div>
                      </div>
                    </div>
                  </a-col>
                </a-row>
              </a-card>
            </a-col>
            <a-col v-if="fourColShow" :flex="4.5" style="width: 0">
              <a-card title="JIT母单">
                <template #extra v-if="state.isAdmin">
                  <span
                    @click="onTabChange('personal', 'card4Key', 'jitPInfo')"
                    :style="{
                      color:
                        state.card4Key === 'personal'
                          ? 'rgba(24, 144, 255, 1)'
                          : 'rgba(78, 89, 105, 1)'
                    }"
                    >个人</span
                  >
                  <span> / </span>
                  <span
                    @click="onTabChange('department', 'card4Key', 'jitPInfo')"
                    :style="{
                      color:
                        state.card4Key === 'department'
                          ? 'rgba(24, 144, 255, 1)'
                          : 'rgba(78, 89, 105, 1)'
                    }"
                    >部门</span
                  >
                </template>
                <a-row type="flex" :gutter="8">
                  <a-col
                    :span="24"
                    v-for="(item, index) in jitPInfo"
                    :key="index"
                  >
                    <div class="card-list">
                      <div class="card-list-item">
                        <div>{{ item.label }}</div>
                        <div class="card-list-item-desc">
                          <span
                            @click="
                              orderPurchaseInfoClickHandler(
                                item,
                                state.card4Key,
                                true
                              )
                            "
                            class="card-list-item-value"
                          >
                            {{ item.value }}
                            <span>条</span>
                          </span>
                        </div>
                      </div>
                      <div class="card-list-line" />
                      <div class="card-list-item">
                        <div>关联SKC</div>
                        <div class="card-list-item-desc">
                          <span
                            @click="
                              orderPurchaseInfoClickHandler(
                                item,
                                state.card4Key,
                                true
                              )
                            "
                            class="card-list-item-value"
                          >
                            {{ item.skcValue }}
                            <span>件</span>
                          </span>
                        </div>
                      </div>
                    </div>
                  </a-col>
                </a-row>
              </a-card>
            </a-col>
            <a-col v-if="fiveColShow" :flex="4.5" style="width: 0">
              <a-card title="JIT子单">
                <template #extra v-if="state.isAdmin">
                  <span
                    @click="onTabChange('personal', 'card5Key', 'jitCInfo')"
                    :style="{
                      color:
                        state.card5Key === 'personal'
                          ? 'rgba(24, 144, 255, 1)'
                          : 'rgba(78, 89, 105, 1)'
                    }"
                    >个人</span
                  >
                  <span> / </span>
                  <span
                    @click="onTabChange('department', 'card5Key', 'jitCInfo')"
                    :style="{
                      color:
                        state.card5Key === 'department'
                          ? 'rgba(24, 144, 255, 1)'
                          : 'rgba(78, 89, 105, 1)'
                    }"
                    >部门</span
                  >
                </template>
                <a-row type="flex" :gutter="8">
                  <a-col
                    :span="24"
                    v-for="(item, index) in jitCInfo"
                    :key="index"
                  >
                    <div class="card-list">
                      <div class="card-list-item">
                        <div>{{ item.label }}</div>
                        <div class="card-list-item-desc">
                          <span
                            @click="toJit(item)"
                            class="card-list-item-value"
                          >
                            {{ item.value }}
                            <span>条</span>
                          </span>
                        </div>
                      </div>
                      <div class="card-list-line" />
                      <div class="card-list-item">
                        <div>关联SKC</div>
                        <div class="card-list-item-desc">
                          <span
                            @click="toJit(item)"
                            class="card-list-item-value"
                          >
                            {{ item.skcValue }}
                            <span>件</span>
                          </span>
                        </div>
                      </div>
                    </div>
                  </a-col>
                </a-row>
              </a-card>
            </a-col>
          </a-row>
        </a-col>
      </a-row>
    </a-form>
    <a-card
      class="select-card"
      :style="{
        height: state.selectDown ? '200px' : '31px'
      }"
    >
      <div @click="selectDirection">
        <span>展示项目选择</span>
        <span v-if="state.selectDown">
          <a-icon type="down" style="font-size: 10px"
        /></span>
        <span v-else> <a-icon type="up" style="font-size: 10px" /></span>
      </div>
      <Transition name="check-box">
        <div class="check-box-container" v-if="state.checkBoxShow">
          <a-checkbox-group
            style="
              display: flex;
              flex-direction: column;
              line-height: 30px;
              font-weight: normal;
            "
            v-model="state.checkedList"
            :options="state.plainOptions"
            @change="onChange"
          />
        </div>
      </Transition>
    </a-card>
    <a-tabs
      v-model="pageInfo.activeKey"
      size="large"
      class="mt10"
      @change="tabChangeHandler"
      v-if="false"
    >
      <a-tab-pane :key="1" tab="我的待办" />
      <a-tab-pane :key="2" tab="我已办结" />
      <a-tab-pane :key="3" tab="我的发起" />
    </a-tabs>
    <!-- 按钮 -->
    <!-- 催单，备注，导出，分配他人，流程查看 -->
    <a-space
      wrap="wrap"
      style="margin-top: 10px; justify-content: space-between; width: 100%"
    >
      <a-space wrap>
        <!-- 点击,发送催单 -->
        <a-button
          size="small"
          type="primary"
          @click="sendReminderBatch"
          :loading="state.reminderLoading"
          v-if="false"
          :disabled="state.reminderDisabledFlag"
        >
          催单
        </a-button>
        <a-button
          size="small"
          type="primary"
          @click="remarkHandler"
          v-if="false"
        >
          备注
        </a-button>
        <a-button size="small" type="primary" @click="completeTaskBatch">
          全部标为完成
        </a-button>
        <a-button
          size="small"
          type="primary"
          @click="todoTableExportExcel"
          :loading="state.exportLoading"
          v-if="false"
        >
          导出
        </a-button>
        <a-button
          size="small"
          @click="showSlaConfig"
          type="primary"
          v-if="false"
        >
          SLA配置
        </a-button>
      </a-space>
    </a-space>
    <!--    menu-name="todoData"-->
    <!--  我的待办table  -->
    <div>
      <remote-table
        ref="todoTable"
        v-if="state.todoTableShow"
        class="todo-table"
        menu-name="todoNotification"
        :show-selection="false"
        :has-export="false"
        :show-setting="false"
        :has-action="true"
        :has-refresh="false"
        :has-reset="false"
        :y="state.y"
        :sy="state.y"
        :row-key="(record, index) => index"
        :api-params="state.todoTableParams"
        interface-u-r-l="/todo/page"
        @change="todoTableChange"
        :column-width="{
          task: 450
        }"
      >
        <template slot="action" slot-scope="{ record }">
          <a
            class="table-btns"
            @click="bomJumpToPage(record, record.addressRoute, 1)"
            v-if="!state.isAdmin && record.recordOperationType === 1"
            >去处理</a
          >
          <a
            class="table-btns"
            v-if="false && !record.reminderFlg"
            @click="sendReminder(record)"
            >催单</a
          >
          <a class="table-btns" v-if="false" @click="remarkHandler(record)"
            >备注</a
          >
          <a
            class="table-btns"
            @click="openAllocationModal(record)"
            v-if="record.recordOperationType === 1"
            >分配他人</a
          >
          <a-popover
            placement="left"
            :visiable="state.showProcessModal"
            trigger="click"
          >
            <template #content>
              <div class="process-timeline pt10">
                <a-spin :spinning="state.processModalSpinning">
                  <a-timeline>
                    <a-timeline-item
                      v-for="item in state.processArr"
                      :key="item.id"
                      color="green"
                    >
                      <p>{{ item.text }}</p>
                      <p>{{ item.operationTime }}</p>
                    </a-timeline-item>
                  </a-timeline>
                </a-spin>
              </div>
            </template>
            <a @click="openProcessModal(record)"> 流程查看 </a>
          </a-popover>
          <a-popconfirm
            title="是否确定将该条待办标为完成？"
            ok-text="确定"
            cancel-text="取消"
            @confirm="completeOneTask(record, record.addressRoute, 1)"
          >
            <a class="table-btns" v-if="record.recordOperationType === 1"
              >标为完成</a
            >
          </a-popconfirm>
        </template>
        <template slot="taskCR" slot-scope="{ record }">
          <a-space>
            <span>
              {{ record.task }}
              <a
                style="white-space: nowrap"
                @click="bomJumpToPage(record, record.taskAddress, 0)"
                >点击查看</a
              >
            </span>
          </a-space>
        </template>
        <template slot="cpCR" slot-scope="{ record }">
          <span>{{ transNullVal(record, 'cp') }}</span>
        </template>
        <template slot="productImgCR" slot-scope="{ record }">
          <img
            v-if="record.productImg"
            style="max-width: 100px; max-height: 100px"
            loading="lazy"
            v-view-img
            :src="record.productImg"
          />
          <img
            v-else
            style="max-width: 100px; max-height: 100px"
            loading="lazy"
            v-view-img
            :src="cupsheImg"
          />
        </template>
        <template slot="businessTypeCR" slot-scope="{ record }">
          <span>{{ transBusinessType(record.businessType) }}</span>
        </template>
        <template slot="initiatorCR" slot-scope="{ record }">
          <span>{{ record.initiatorName }}</span>
        </template>
        <template slot="recordOperationTimeCR" slot-scope="{ record }">
          <span>{{ transNullVal(record, 'recordOperationTime') }}</span>
        </template>
        <template slot="recordOperationTypeCR" slot-scope="{ record }">
          <span>{{ transState(record.recordOperationType) }}</span>
        </template>
        <template slot="remarkCR" slot-scope="{ record }">
          <a v-if="record.remark" @click="remarkHistoryHandler(record)">{{
            transNullVal(record, 'remark')
          }}</a>
          <span v-else>-</span>
        </template>
      </remote-table>
    </div>
    <!-- 分配他人弹框 -->
    <allocationModal
      :show-allocation-modal="state.showAllocationModal"
      @closeModal="allocationModalClose"
      :record="state.nowTaskObj"
      @refresh="refreshTable"
    />
    <!--  SLA配置弹框  -->
    <slaConfigModal
      :show-sla-config-modal="state.showSlaConfigModal"
      :sla-type-options="state.slaTypeOptions"
      @closeModal="slaConfigModalClose"
    />
    <!--  添加备注弹框  -->
    <remarkAddModal
      :show-add-remark-modal="state.showAddRemarkModal"
      :ids="state.remarkTableId"
      @closeModal="remarkModalClose"
      @refresh="refreshTable"
    />
    <!-- 备注历史弹框 -->
    <remarkHistoryModal
      :show-remark-modal="state.showRemarkModal"
      :table-id="state.remarkHistoryId"
      @closeModal="remarkHistoryModalClose"
    />
  </div>
</template>
<script>
import {
  todo_complete_post,
  todo_workflow_post,
  todo_complete_one_task,
  todo_complete_task_batch,
  todo_classification_count_normal,
  todo_classification_count_admin,
  todo_send_reminder_post,
  todo_is_admin,
  todo_sla_list_type,
  todo_count_purchase,
  todo_count_reconciliation,
  todo_count_inquiry,
  todo_count_purchase_department,
  todo_count_reconciliation_department,
  todo_count_inquiry_department,
  todo_export_post
} from 'server/modules/7537'
import { Modal } from 'ant-design-vue'
import { downloadFile } from 'utils/file.js'
import remarkAddModal from '@/components/todoTable/module/remarkAddModal.vue'
import remarkHistoryModal from './module/remarkHistoryModal.vue'
import slaConfigModal from './module/slaConfigModal.vue'
import allocationModal from './module/allocationModal.vue'
import { postMessageToParent } from 'cupshe-utils'
import { procPurchaseJit } from '@/apis/17359'
export default {
  name: 'TodoTableContent',
  components: {
    remarkAddModal,
    remarkHistoryModal,
    slaConfigModal,
    allocationModal
  },
  data() {
    return {
      state: {
        userId: null,
        y: window.innerHeight - 300,
        form: this.$form.createForm(this),
        // 表格请求
        tableParams: {
          recordOperationType: [],
          tab: 1
        },
        // 表格请求参数枚举
        stateOptions: [
          // {
          //   optionName: '发起',
          //   value: 0
          // },
          {
            optionName: '处理中',
            value: 1
          },
          {
            optionName: '转移',
            value: 3
          },
          {
            optionName: '完成',
            value: 2
          }
        ],
        // 页面操作栏点击时，任务内容
        nowTaskObj: {},
        // 分配他人弹框
        showAllocationModal: false,
        // SLA配置弹窗
        showSlaConfigModal: false,
        // 添加备注弹框
        showAddRemarkModal: false,
        // 备注弹框
        showRemarkModal: false,
        allocationModalSpinning: false,
        // 可分配的对象 ，根据不同业务，导入不同的人
        allocationOptions: [],
        // 被选择分配的对象
        assignedID: null,
        loadingCreateSlaConfigBtn: false,
        // 控制分配弹窗-确定按钮Loading
        loadingConfirmAllocationBtn: false,
        // 流程查看弹窗
        showProcessModal: false,
        processArr: [],
        maxHeight: 300,
        processModalSpinning: false,
        slaTypeOptions: [],
        alarmDuration: null,
        timeoutDuratiojn: null,
        remarkHistoryId: null,
        remarkTableId: [],
        isAdmin: false,
        todoTableParams: {
          receiver: []
        },
        todoTableInterfaceUrl: '',
        plainOptions: [
          {
            label: '订单采购',
            value: 'orderPurchase'
          },
          {
            label: '对账任务',
            value: 'checkAccount'
          },
          {
            label: '询期',
            value: 'inquiry'
          },
          {
            label: 'JIT母单',
            value: 'jitM'
          },
          {
            label: 'JIT子单',
            value: 'jitC'
          }
        ],
        checkedList: [],
        indeterminate: true,
        checkAll: false,
        card1Key: 'personal',
        card2Key: 'personal',
        card3Key: 'personal',
        card4Key: 'personal',
        card5Key: 'personal',
        todoKey: 'personal',
        selectOpen: false,
        personalUser: null,
        departmentUser: [],
        reminderDisabledFlag: false,
        reminderLoading: false,
        exportLoading: false,
        todoTableShow: false,
        selectDown: false,
        checkBoxShow: false,
        todoSelectRowKeys: [],
        todoTableData: []
      },
      pageInfo: {
        activeKey: 1,
        selectedRowKeys: []
      },
      todoHeaderInfo: {
        processing: 0,
        initiation: 0,
        categoricalStatistics: []
      },
      // 订单采购
      orderPurchaseInfo: [],
      // 对账任务
      checkAccountInfo: [],
      // 询期
      inquiryInfo: [],
      jitCInfo: [],
      jitPInfo: []
    }
  },
  computed: {
    firstColShow() {
      return (
        this.state.checkedList.length > 0 &&
        this.state.checkedList.find(item => item === 'orderPurchase')
      )
    },
    secondColShow() {
      return (
        this.state.checkedList.length > 0 &&
        this.state.checkedList.find(item => item === 'checkAccount')
      )
    },
    thirdColShow() {
      return (
        this.state.checkedList.length > 0 &&
        this.state.checkedList.find(item => item === 'inquiry')
      )
    },
    fourColShow() {
      return (
        this.state.checkedList.length &&
        this.state.checkedList.find(item => item === 'jitM')
      )
    },
    fiveColShow() {
      return (
        this.state.checkedList.length &&
        this.state.checkedList.find(item => item === 'jitC')
      )
    }
  },
  mounted() {
    // 待办类型统计URL
    const checkedList = localStorage.getItem('todoCardCheckedList')
    if (checkedList) {
      this.state.checkedList = JSON.parse(checkedList)
    } else {
      this.state.checkedList = [
        'orderPurchase',
        'checkAccount',
        'inquiry',
        'jitM',
        'jitC'
      ]
    }
    if (this.state.checkedList.length > 0) {
      this.onChange(this.state.checkedList)
    }
    // 判断当前登陆人是否为admin
    todo_is_admin().then(res => {
      this.state.personalUser = res.data ? res.data.userId : null
      if (res.data?.isAdmin === 1) {
        // 当前用户为admin
        this.state.isAdmin = true
        this.state.todoTableParams.receiver = res.data.staffList
        this.state.departmentUser = res.data.staffList
        this.state.todoTableShow = true
      } else {
        this.state.isAdmin = false
        this.state.todoTableShow = true
      }
      this.$nextTick(() => {
        this.$watch(
          'state.todoTableData',
          val => {
            if (val.length > 0) {
              const flag = val.some(item => item.reminderFlg === null)
              if (flag) {
                this.state.reminderDisabledFlag = false
              } else {
                this.state.reminderDisabledFlag = true
              }
            }
          },
          { immediate: true, deep: true }
        )
      })
      todo_classification_count_normal().then(res => {
        this.todoHeaderInfo.processing = res.data.processing
          ? res.data.processing
          : 0
        this.todoHeaderInfo.initiation = res.data.initiation
          ? res.data.initiation
          : 0
        // 将res.data.categoricalStatistics 拷贝到this.todoHeaderInfo
        res.data.categoricalStatistics.forEach(item => {
          item.value = item.value ? item.value : 0
          this.todoHeaderInfo.categoricalStatistics.push(item)
        })
      })
    })
  },
  methods: {
    async completeOneTask(elem) {
      const { success, retInfo, data } = await todo_complete_one_task(elem)
      if (success) {
        this.todoHeaderInfo.categoricalStatistics = []
        this.$message.success(data)
        this.$emit('todoComplete', elem)
        this.search()
        todo_classification_count_normal().then(res => {
          this.todoHeaderInfo.processing = res.data.processing
          this.todoHeaderInfo.initiation = res.data.initiation
          // 将res.data.categoricalStatistics 拷贝到this.todoHeaderInfo
          res.data.categoricalStatistics.forEach(item => {
            item.value = item.value ? item.value : 0
            this.todoHeaderInfo.categoricalStatistics.push(item)
          })
        })
      } else {
        this.$message.error(retInfo)
        console.log(retInfo)
      }
    },
    async completeTaskBatch(val) {
      const self = this
      Modal.confirm({
        content: '是否确定将待办任务全部标为完成？',
        okText: '确定',
        cancelText: '取消',
        onOk: async function () {
          const { success, retInfo, data } = await todo_complete_task_batch(val)
          if (success) {
            self.todoHeaderInfo.categoricalStatistics = []
            self.$message.success(data)
            self.search()
            todo_classification_count_normal().then(res => {
              self.todoHeaderInfo.processing = res.data.processing
              self.todoHeaderInfo.initiation = res.data.initiation
              // 将res.data.categoricalStatistics 拷贝到this.todoHeaderInfo
              res.data.categoricalStatistics.forEach(item => {
                item.value = item.value ? item.value : 0
                self.todoHeaderInfo.categoricalStatistics.push(item)
              })
            })
          } else {
            self.$message.error(retInfo)
          }
        }
      })
    },
    // 字典翻译
    transBusinessType(val) {
      let res = null
      if (val) {
        switch (val) {
          case 1:
            res = '调整工艺'
            break
          case 2:
            res = '款式核价'
            break
          case 10:
            res = '重新核价'
            break
          case 3:
          case 4:
          case 5:
          case 6:
          case 7:
          case 9:
            res = '样衣评审'
            break
        }
        return res
      } else {
        return '-'
      }
    },
    transNullVal(elem, attribute) {
      if (elem[attribute]) {
        return elem[attribute]
      } else {
        return '-'
      }
    },
    transState(val) {
      let res = null
      if (val) {
        switch (val) {
          case 0:
            res = '发起'
            break
          case 1:
            res = '处理中'
            break
          case 2:
            res = '完成'
            break
          case 3:
            res = '转移'
            break
        }
        return res
      } else {
        return '-'
      }
    },
    search() {
      this.$refs.todoTable.refresh()
    },
    recordOperationTypeChange(val) {
      if (val?.length === 0) {
        this.search()
      }
    },
    // 去处理，根据数据内容跳转到指定页
    toDispose(record) {
      console.log(record)
    },
    // 分配给他人弹窗
    openAllocationModal(record) {
      this.state.nowTaskObj = record
      this.state.showAllocationModal = true
    },
    closeAllocationModal() {
      this.state.showAllocationModal = false
      this.state.loadingConfirmAllocationBtn = false
    },
    // 查看某个任务的流程
    async openProcessModal(record) {
      this.state.processArr = []
      this.state.processModalSpinning = true
      const { success, retInfo, data } = await todo_workflow_post({
        workFlowCode: record.workFlowCode,
        businessType: record.businessType
      })
      if (success) {
        this.state.processArr = data
      } else {
        console.log(retInfo)
      }
      this.state.showProcessModal = true
      this.state.processModalSpinning = false
    },
    // 完成待办
    async todoComplete(params) {
      const { success, retInfo, data } = await todo_complete_post(params)
      if (success) {
        this.$message.success(data)
      } else {
        console.log(retInfo)
      }
    },
    // BOM相关操作，跳转到指定地址
    async bomJumpToPage(record, url, index) {
      if (record.businessType === 9 && index === 1) {
        await this.todoComplete({
          cp: record.cp,
          businessDataCode: record.businessDataCode,
          businessModelCode: record.businessModelCode
        })
        this.$refs.todoTable.refresh()
      }
      if (!url) {
        this.$message.error('跳转地址参数为空')
      }
      const self = this
      const pathStart = url.indexOf('/#/')

      const questionMarkIndex = url.indexOf('?')
      const params = new URLSearchParams(url.substring(questionMarkIndex + 1))

      const paramsObject = {}
      params.forEach(function (value, key) {
        paramsObject[key] = value
      })

      let pathStr = null
      let system = null
      if (url.indexOf('PLM2') !== -1) {
        system = 2
        pathStr = url.substring(pathStart + 3, questionMarkIndex)
      } else if (url.indexOf('PLM3') !== -1) {
        system = 3
        pathStr = url.substring(pathStart + 3, questionMarkIndex)
      }
      const option = {
        params: paramsObject,
        system: system
      }
      let title = null
      // 后续改为接口动态传值
      if (pathStr === 'bom') {
        title = 'BOM列表'
      } else {
        title = 'CP卡片'.concat(record.cp)
      }
      self.useJumpToPage(title, pathStr, option)
    },
    async sendReminderBatch() {
      const selectedRow = this.state.todoTableData.filter((value, index) => {
        if (this.state.todoSelectRowKeys.includes(index)) {
          return value
        }
      })
      if (selectedRow.length === 0) {
        this.$message.error('请选择需要催单的数据')
        return
      }
      this.state.reminderLoading = true
      const ids = selectedRow.map(({ id }) => id)
      const { success, retInfo, data } = await todo_send_reminder_post({
        ids
      })
      if (success) {
        this.$refs.todoTable.refresh()
        this.$message.success(data)
      } else {
        console.log(retInfo)
      }
      this.state.reminderLoading = false
    },
    async sendReminder(record) {
      const { success, retInfo, data } = await todo_send_reminder_post({
        ids: [record.id]
      })
      if (success) {
        this.$refs.todoTable.refresh()
        this.$message.success(data)
      } else {
        console.log(retInfo)
      }
    },
    showSlaConfig() {
      todo_sla_list_type().then(res => {
        this.state.slaTypeOptions = res.data
        const _this = this
        // 惰性函数，防止多次调用请求
        this.showSlaConfig = function () {
          _this.state.showSlaConfigModal = true
        }
        this.showSlaConfig()
      })
    },
    remarkHistoryHandler(record) {
      this.state.showRemarkModal = true
      this.state.remarkHistoryId = record.id
    },
    remarkHandler(record) {
      if (!record?.id && this.state.todoSelectRowKeys.length === 0) {
        this.$message.error('请选择一条记录')
        return
      }
      this.state.remarkTableId = record?.id ? [record.id] : []
      if (this.state.remarkTableId.length === 0) {
        const selectedRow = this.state.todoTableData.filter((value, index) => {
          if (this.state.todoSelectRowKeys.includes(index)) {
            return value
          }
        })
        this.state.remarkTableId = selectedRow.map(({ id }) => id)
      }
      this.state.showAddRemarkModal = true
    },
    tabChangeHandler(val) {
      this.state.tableParams.tab = val
      this.$nextTick(() => {
        this.$refs.todoTable.refresh()
      })
    },
    todoTableExportExcel() {
      this.state.exportLoading = true
      todo_export_post({
        receiver: this.state.todoTableParams.receiver
      }).then(({ success, retInfo, data }) => {
        if (success) {
          downloadFile(data)
        } else {
          this.$message.error(retInfo)
        }
        this.state.exportLoading = false
      })
    },
    todoTypeClickHandler(val) {
      val = [...new Set(val)]
      const queryInfo = {}
      if (val.length > 0) {
        queryInfo.cps = val
      }
      this.jumpToPage(
        '产品开发管理',
        'productDesign/waitDesignInfo',
        queryInfo,
        2
      )
      // this.useJumpToPage('产品开发管理', 'productDesign/waitDesignInfo', {
      //   isDelete: true,
      //   system: 2,
      //   params: {
      //     ...queryInfo
      //   }
      // })
      // setTimeout(() => {
      //   this.useJumpToPage('产品开发管理', 'productDesign/waitDesignInfo', {
      //     system: 2,
      //     params: {
      //       ...queryInfo
      //     }
      //   })
      // }, 800)
    },
    async onChange(checkedList) {
      let url = null
      checkedList.forEach(async item => {
        let infoList = null
        if (item === 'orderPurchase') {
          url =
            this.state.card1Key === 'personal'
              ? todo_count_purchase
              : todo_count_purchase_department
          infoList = 'orderPurchaseInfo'
        } else if (item === 'checkAccount') {
          url =
            this.state.card2Key === 'personal'
              ? todo_count_reconciliation
              : todo_count_reconciliation_department
          infoList = 'checkAccountInfo'
        } else if (item === 'inquiry') {
          url =
            this.state.card3Key === 'personal'
              ? todo_count_inquiry
              : todo_count_inquiry_department
          infoList = 'inquiryInfo'
        } else if (item === 'jitM') {
          url =
            this.state.card4Key === 'personal'
              ? procPurchaseJit.jit_parent_statistics_get
              : procPurchaseJit.jit_parent_statistics_department_get
          infoList = 'jitPInfo'
        } else if (item === 'jitC') {
          url =
            this.state.card5Key === 'personal'
              ? procPurchaseJit.jit_statistics_get
              : procPurchaseJit.jit_statistics_department_get
          infoList = 'jitCInfo'
        }
        const { success, retInfo, data } = await url()
        if (success) {
          data.forEach(item => {
            item.value = item.value ? item.value : 0
            item.skcValue = item.skcValue ? item.skcValue : 0
          })
          this[infoList] = data
        } else {
          this.$message.error(retInfo)
        }
      })
      localStorage.setItem('todoCardCheckedList', JSON.stringify(checkedList))
      this.state.indeterminate =
        !!checkedList.length &&
        checkedList.length < this.state.plainOptions.length
      this.state.checkAll =
        checkedList.length === this.state.plainOptions.length
    },
    jumpToPage(title, path, params, system = 2) {
      const t = 't=' + Date.now()
      let queryStr = [t]
      Object.keys(params).forEach(key => {
        queryStr.push(`${key}=${params[key]}`)
      })
      if (queryStr.length) {
        queryStr = '?' + queryStr.join('&')
      }
      console.log(
        `${
          system === 3 ? process.env.VUE_APP_PLM3 : process.env.VUE_APP_PLM2
        }/#/${path}${queryStr}`
      )
      console.log(
        `${
          system === 3 ? process.env.VUE_APP_PLM3 : process.env.VUE_APP_PLM2
        }/#/${path}?t=${t}`
      )
      if (window.env_local) {
        window.open(
          `${
            system === 3 ? process.env.VUE_APP_PLM3 : process.env.VUE_APP_PLM2
          }/#/${path}${queryStr}`
        )
      } else {
        console.log('plm')
        postMessageToParent({
          type: 'breadcrumb',
          menuPath: `${
            system === 3 ? process.env.VUE_APP_PLM3 : process.env.VUE_APP_PLM2
          }/#/${path}${queryStr}`, // 详情从根目录开始的完整路由
          menuName: title, // 面包屑名称
          basePath: `${
            system === 3 ? process.env.VUE_APP_PLM3 : process.env.VUE_APP_PLM2
          }/#/${path}?t=${t}` // 详情从根目录开始基础路由
        })
      }
    },
    async onTabChange(key, type, info) {
      let url = null
      switch (type) {
        case 'card1Key':
          if (key === 'personal') {
            url = todo_count_purchase
          } else {
            url = todo_count_purchase_department
          }
          break
        case 'card2Key':
          if (key === 'personal') {
            url = todo_count_reconciliation
          } else {
            url = todo_count_reconciliation_department
          }
          break
        case 'card3Key':
          if (key === 'personal') {
            url = todo_count_inquiry
          } else {
            url = todo_count_inquiry_department
          }
          break
        case 'card4Key':
          if (key === 'personal') {
            url = procPurchaseJit.jit_parent_statistics_get
          } else {
            url = procPurchaseJit.jit_parent_statistics_department_get
          }
          break
        case 'card5Key':
          if (key === 'personal') {
            url = procPurchaseJit.jit_statistics_get
          } else {
            url = procPurchaseJit.jit_statistics_department_get
          }
          break
      }
      const { success, retInfo, data } = await url()
      if (success) {
        if (data.length > 0) {
          data.forEach(item => {
            item.value = item.value ? item.value : 0
            item.skcValue = item.skcValue ? item.skcValue : 0
          })
          this[info] = data
        }
      } else {
        this.$message.error(retInfo)
      }
      this.state[type] = key
    },
    onTodoCardTabChange(key, type) {
      this.state[type] = key
      this.todoHeaderInfo.categoricalStatistics = []
      let url = todo_classification_count_admin
      if (key === 'personal') {
        url = todo_classification_count_normal
      } else {
        url = todo_classification_count_admin
      }
      url().then(res => {
        this.todoHeaderInfo.processing = res.data.processing
          ? res.data.processing
          : 0
        this.todoHeaderInfo.initiation = res.data.initiation
          ? res.data.initiation
          : 0
        // 将res.data.categoricalStatistics 拷贝到this.todoHeaderInfo
        res.data.categoricalStatistics.forEach(item => {
          item.value = item.value ? item.value : 0
          this.todoHeaderInfo.categoricalStatistics.push(item)
        })
      })
    },
    toJit(item) {
      console.log(item, 111)
      this.jumpToPage(
        'JIT子单管理',
        'JitManagement',
        {
          fromTodo: true,
          key: this.state.card4Key,
          dataKey: item.key
        },
        3
      )
    },
    checkAccountInfoClickHandler(val, flag) {
      let menuName = '采购对账管理'
      switch (val.key) {
        case 'finish':
          menuName = '采购对账管理(已完成)'
          break
        case 'unFinish':
          menuName = '采购对账管理(未完成)'
          break
      }
      const queryInfo = {
        key: this.state.card2Key,
        dataKey: val.key
      }
      // if (val.value > 0) {
      //   if (this.state.personalUser || this.state.departmentUser.length > 0) {
      //     queryInfo.purchaserId =
      //       this.state.card2Key === 'personal'
      //         ? this.state.personalUser
      //         : this.state.departmentUser
      //   }
      // }
      // if (val.dataList?.length > 0) {
      //   queryInfo.dataList = val.dataList
      // }
      this.jumpToPage(menuName, 'PurchaseStatement', queryInfo, 3)
      // this.useJumpToPage(menuName, 'PurchaseStatement', {
      //   isDelete: true,
      //   system: 3,
      //   params: {
      //     ...queryInfo
      //   }
      // })
      // setTimeout(() => {
      //   this.useJumpToPage(menuName, 'PurchaseStatement', {
      //     system: 3,
      //     params: {
      //       ...queryInfo
      //     }
      //   })
      // }, 800)
    },
    orderPurchaseInfoClickHandler(val, cardkey, isjit) {
      const menuName = '采购订单-已审核'
      // const purchaseCodes = val.purchaseCodes
      const queryInfo = {
        key: cardkey,
        dataKey: val.key
      }
      if (isjit) {
        queryInfo.isjit = true
      }
      // if (purchaseCodes?.length > 0) {
      //   queryInfo.purchaseCodes = purchaseCodes
      // }
      this.jumpToPage(
        menuName,
        'purchasingManagement/POmanagement/hasAudited',
        queryInfo,
        2
      )
      // this.useJumpToPage(
      //   menuName,
      //   'purchasingManagement/POmanagement/hasAudited',
      //   {
      //     isDelete: true,
      //     system: 2,
      //     params: {
      //       ...queryInfo
      //     }
      //   }
      // )
      // setTimeout(() => {
      //   this.useJumpToPage(
      //     menuName,
      //     'purchasingManagement/POmanagement/hasAudited',
      //     {
      //       system: 2,
      //       params: {
      //         ...queryInfo
      //       }
      //     }
      //   )
      // }, 800)
    },
    inquiryClickHandler(val) {
      const queryInfo = {
        key: this.state.card3Key
      }
      // if (codeList && codeList.length > 0) {
      //   queryInfo.codeList = val.codeList
      // }
      const menuName = '询期计划:' + val.value
      this.jumpToPage(menuName, 'InquiryPeriodDetail', queryInfo, 3)
      // this.useJumpToPage(menuName, 'InquiryPeriodDetail', {
      //   isDelete: true,
      //   system: 3,
      //   params: {
      //     ...queryInfo
      //   }
      // })
      // setTimeout(() => {
      //   this.useJumpToPage(menuName, 'InquiryPeriodDetail', {
      //     system: 3,
      //     params: {
      //       ...queryInfo
      //     }
      //   })
      // }, 800)
    },
    remarkModalClose() {
      this.state.remarkTableId = []
      this.state.showAddRemarkModal = false
    },
    remarkHistoryModalClose() {
      this.state.showRemarkModal = false
    },
    // 刷新table
    refreshTable() {
      this.$refs.todoTable.refresh()
    },
    // 关闭sla配置弹框
    slaConfigModalClose() {
      this.state.showSlaConfigModal = false
    },
    allocationModalClose() {
      this.state.showAllocationModal = false
    },
    selectDirection() {
      this.state.selectDown = !this.state.selectDown
      if (this.state.selectDown) {
        this.state.checkBoxShow = true
      } else {
        this.state.checkBoxShow = false
      }
    },
    todoTableChange(selectRowKeys) {
      this.state.todoSelectRowKeys = selectRowKeys
    }
  }
}
</script>
<style scoped lang="less">
.table-btns {
  margin-right: 8px;
  white-space: nowrap;
}

.main-content {
  margin: 0 auto;
  display: flex;
  flex-direction: column;
  height: 100%;
}
.process-timeline {
  max-height: 300px;
  min-height: 50px;
  overflow-y: auto;
}
::v-deep.ant-card {
  height: calc(100% - 10px);
  font-family: 'HarmonyOS Sans SC';
  border: 1px solid #e8e8e8;
  box-shadow: 0 0 8px 0 rgba(0, 0, 0, 0.15);
  margin-bottom: 10px;
  transition: all 0.5s ease;
  .ant-tabs {
    .ant-tabs-tab {
      padding: 0 0 5px 0;
    }
    .ant-tabs-nav-container {
      font-size: 14px !important;
    }
  }
  .ant-card-head {
    padding: 0 !important;
    border-bottom: 0px;
    .ant-card-head-title {
      font-weight: 500;
      min-height: auto !important;
      font-size: 18px;
      letter-spacing: 0px;
      color: rgba(29, 33, 41, 1);
      text-align: left;
      vertical-align: middle;
      margin: 15px 0 10px 16px;
      padding: 0px;
    }
    .ant-card-extra {
      font-size: 12px;
      font-weight: 500;
      letter-spacing: 0px;
      line-height: 29.35px;
      padding: 0px;
      margin: 16px 27px 12px 0;
      span:first-of-type,
      span:last-of-type {
        cursor: pointer;
      }
    }
  }
  .ant-card-body {
    margin: 0 16px 20px 17px;
    padding: 0px !important;
    .ant-row-flex {
      row-gap: 12px;
      p {
        margin-bottom: 0;
      }
    }
    .card-list {
      display: flex;
      align-items: center;
      border-radius: 4px;
      background: rgba(247, 248, 250, 1);
      &-line {
        border-left: 1px solid #c0bcbc;
        height: 25px;
        flex: 0.5;
        margin: 0 2px;
        transform: translateX(50%);
      }
      &-item {
        font-weight: normal;
        display: flex;
        flex-direction: column;
        font-size: 12px;
        font-weight: 500;
        letter-spacing: 0px;
        line-height: 20px;
        color: rgba(78, 89, 105, 1);
        text-align: left;
        vertical-align: middle;
        flex: 1;
        &:first-of-type {
          margin: 16px 0 4px 12px;
        }
        &:last-of-type {
          margin: 16px 8px 4px 0;
        }
        &-desc {
          display: flex;
          align-items: center;
          justify-content: space-between;
          text-align: left;
          vertical-align: top;
          .card-list-item-value {
            width: 0;
            font-size: 20px;
            font-weight: 700;
            line-height: 37.35px;
            color: rgba(29, 33, 41, 1);
            flex-grow: 1;
            span {
              font-size: 12px;
              font-weight: 500;
              letter-spacing: 0px;
              line-height: 26.68px;
              color: rgba(134, 144, 156, 1);
            }
            &:hover {
              cursor: pointer;
              color: #1890ff;
            }
          }
          .ant-select {
            width: 100%;
          }
        }
        &-unit {
          color: gray;
          margin-left: 5px;
        }
      }
    }
  }
}
:deep(.select-card) {
  z-index: 999;
  font-size: 14px;
  font-weight: 500;
  letter-spacing: 0px;
  line-height: 22px;
  color: rgba(29, 33, 41, 1);
  text-align: left;
  vertical-align: top;
  position: absolute;
  top: 0;
  right: 80px;
  line-height: 30px;
  width: 200px;
  box-shadow: none;
  border-top: 0px;
  padding: 0 10px;
  .ant-card-body {
    display: flex;
    flex-direction: column;
    margin: 0;
    height: 100%;
    & > div:first-child {
      display: flex;
      justify-content: space-between;
      &:hover {
        cursor: pointer;
      }
    }
    .check-box-container {
      padding: 0 10px !important;
      overflow: hidden;
      margin-top: 10px;
      background: #f7f8fa;
      border-radius: 4px;
      flex-grow: 1;
      margin-bottom: 10px;
    }
  }
  .check-box-enter,
  .check-box-leave-to {
    opacity: 0;
  }

  .check-box-enter-to,
  .check-box-leave {
    opacity: 1;
  }
}
:deep(.inquiry-card) {
  .card-list-item {
    margin-left: 12px !important;
  }
}
.check-box-enter-active,
.check-box-leave-active {
  transition: all 0.5s ease;
}
</style>
